<template>
  <!-- 居中容器，宽度占50% -->
  <div class="form-container">
    <a-form
      :model="editParam"
      @finish="doSubmit"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <!-- 用户头像 -->
      <a-form-item label="用户头像">
        <a-image
          :src="editParam.userAvatar"
          width="100px"
          v-if="editParam.userAvatar"
        />
      </a-form-item>

      <!-- 用户昵称 -->
      <a-form-item label="用户昵称">
        <a-input v-model:value="editParam.userName" />
      </a-form-item>

      <!-- 用户简介（多行文本框） -->
      <a-form-item label="用户简介">
        <a-textarea
          v-model:value="editParam.userProfile"
          :rows="4"
          placeholder="请输入简介"
        />
      </a-form-item>

      <!-- 用户权限级别（下拉框） -->
      <a-form-item label="用户权限级别">
        <a-select v-model:value="editParam.userRole">
          <a-select-option value="user">用户</a-select-option>
          <a-select-option value="admin">管理员</a-select-option>
        </a-select>
      </a-form-item>

      <!-- 操作按钮 -->
      <a-form-item :wrapper-col="{ offset: 6, span: 16 }">
        <a-button type="primary" html-type="submit">确认修改</a-button>
        <a-button style="margin-left: 10px" @click="goBack">返回上一页</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { getUserByIdUsingGet, updateUserUsingPost } from '@/api/userController'
import { message } from 'ant-design-vue'
import router from '@/router'

const editParam = reactive<API.UserUpdateRequest>({})

// 提交表单
const doSubmit = async () => {
  try {
    const res = await updateUserUsingPost(editParam)
    if (res.data.code === 0) {
      message.success('更新成功')
      router.back()
    } else {
      message.error('更新失败')
    }
  } catch (error) {
    message.error('请求失败')
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 初始化加载数据
onMounted(async () => {
  const route = useRoute()
  const id = route.params.id as string

  const res = await getUserByIdUsingGet({ id })
  if (res.data.code === 0) {
    Object.assign(editParam, res.data.data)
  } else {
    message.error('数据获取失败')
    router.back()
  }
})
</script>

<style scoped>
/* 居中容器样式 */
.form-container {
  width: 50%;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
}

/* 调整按钮间距 */
.ant-form-item:last-child {
  margin-top: 24px;
}
</style>
